#pragma once
#include "requestor.hpp"
#include <cstddef>
#include <memory>
#include <mutex>
#include <unordered_map>
#include <vector>



namespace rpc
{
    namespace client
    {
        class Provider
        {
        public:
            using ptr = std::shared_ptr<Provider>;
            Provider(const Requestor::ptr requestor):_requestor(requestor)  
            {}
            bool registryMethod(const BaseConnection::ptr &conn, const std::string &method, const Address &host)
            {
                auto msg_req = MessageFactory::create<ServiceRequest>();
                msg_req->setMethod(method);
                msg_req->setHost(host);
                msg_req->setOptype(ServiceOptype::SERVICE_REGISTRY);
                msg_req->setId(UUID::uuid());
                msg_req->setMtype(MType::REQ_SERVICE);
                BaseMessage::ptr msg_rsp;
                bool ret = _requestor->send(conn, msg_req, msg_rsp);
                if(!ret)
                {
                    ELOG("%s 服务注册失败", method.c_str());
                    return false;
                }
                auto service_rsp = std::dynamic_pointer_cast<ServiceResponse>(msg_rsp);
                if(service_rsp.get() == nullptr)
                {
                    ELOG("向下转换失败");
                    return false;
                }
                if(service_rsp->rcode() != RCode::RCODE_OK)
                {
                    ELOG("服务注册失败，原因：%s",errReason(service_rsp->rcode()).c_str());
                    return false;
                }
                return true;
            }
        private:
            Requestor::ptr _requestor;
        };
        class MethodHost
        {
        public:
            using ptr = std::shared_ptr<MethodHost>;
            MethodHost():_idx(0)
            {}
            MethodHost(const std::vector<Address> &hosts):_hosts(hosts), _idx(0)
            {}
            void appendHost(const Address &host)
            {
                //中途收到服务上线调用
                std::unique_lock<std::mutex> lock(_mutex);
                _hosts.push_back(host);
            }
            void removeHost(const Address &host)
            {
                //中途收到服务下线调用
                std::unique_lock<std::mutex> lock(_mutex);
                for(auto it = _hosts.begin(); it != _hosts.end(); it++)
                {
                    if(*it == host)
                    {
                        _hosts.erase(it);
                        break;
                    }
                }
            }
            Address chooseHost()
            {
                std::unique_lock<std::mutex> lock(_mutex);
                size_t pos = _idx++ % _hosts.size();
                return _hosts[pos];
            }
            bool empty()
            {
                std::unique_lock<std::mutex> lock(_mutex);
                return _hosts.empty();
            }
        private:
            std::mutex _mutex;
            size_t _idx;
            std::vector<Address> _hosts;
        };
        class Discoverer
        {
        public:
            using OfflineCallback = std::function<void(const Address&)>;
            using ptr = std::shared_ptr<Discoverer>;
            Discoverer(const Requestor::ptr &requestor, const OfflineCallback &offline_cb):_offline_cb(offline_cb),
            _requestor(requestor)
            {}
            bool serviceDiscovery(const BaseConnection::ptr &conn, const std::string &method, Address &host)
            {
                //当前锁保管的提供者信息存在，则直接返回地址
                {
                    std::unique_lock<std::mutex> lock(_mutex);
                    auto it = _method_hosts.find(method);
                    if(it != _method_hosts.end())
                    {
                        if(it->second->empty() == false)
                        {
                            host = it->second->chooseHost();
                            return true;
                        }
                    }
                }
                //empty
                auto msg_req = MessageFactory::create<ServiceRequest>();
                msg_req->setMethod(method);
                msg_req->setOptype(ServiceOptype::SERVICE_DISCOVERY);
                msg_req->setId(UUID::uuid());
                msg_req->setMtype(MType::REQ_SERVICE);

                BaseMessage::ptr msg_rsp;
                bool ret = _requestor->send(conn, msg_req, msg_rsp);
                if(!ret)
                {
                    ELOG("服务发现失败!");
                    return false;
                }
                auto service_rsp = std::dynamic_pointer_cast<ServiceResponse>(msg_rsp);
                if(!service_rsp)
                {
                    ELOG("服务发现失败,响应类型转换失败");
                    return false;
                }
                if(service_rsp->rcode()!=RCode::RCODE_OK)
                {
                    ELOG("服务发现失败！%s", errReason(service_rsp->rcode()).c_str());
                    return false;
                }
                //走到这里，代表当前是没有服务提供主机！
                std::unique_lock<std::mutex> lock(_mutex);
                auto method_host = std::make_shared<MethodHost>(service_rsp->hosts());
                if(method_host->empty())
                {
                    ELOG("服务发现失败，没有能够提供服务的主机");
                    return false;
                }
                host = method_host->chooseHost();
                _method_hosts.insert({method, method_host});
                return true;
            }
            //这个接口是提供给Dispatcher模块进行上下线请求处理的回调函数
            void onServiceRequest(const BaseConnection::ptr &conn, const ServiceRequest::ptr &msg)
            {
                //1判断是上线还是下线请求，都不是则不用处理
                auto optype = msg->optype();
                std::unique_lock<std::mutex> lock(_mutex);
                if(optype == ServiceOptype::SERVICE_ONLINE)
                {
                    //2上线：找到MethodHost，向其中新增一个主机地址
                    auto it = _method_hosts.find(msg->method());
                    if(it == _method_hosts.end())
                    {
                        auto method_host = std::make_shared<MethodHost>();
                        method_host->appendHost(msg->host());
                        _method_hosts[msg->method()] = method_host;
                    }
                    else 
                    {
                        it->second->appendHost(msg->host());
                    }
                }
                else if(optype == ServiceOptype::SERVICE_OFFLINE)
                {
                    //3下线：找到MethodHost，向其中删除一个主机地址
                    auto it = _method_hosts.find(msg->method());
                    if(it == _method_hosts.end())
                    {
                        return;
                    }
                    it->second->removeHost(msg->host());
                    _offline_cb(msg->host());
                }
            }
        private:
            std::mutex _mutex;
            OfflineCallback _offline_cb;
            std::unordered_map<std::string, MethodHost::ptr> _method_hosts;
            Requestor::ptr _requestor;
        };
    }
}